module Oos4ruby
class Contact < Bean::BeanClass
  include Bean
  
  define_el_reader AtomNamespace => [:title, :updated]    
  
  attr_writer :trusted
  
  alias :nick :title
  
  def initialize(xml, auth, slug)
    @xml = xml
    @auth = auth
    @slug = slug
  end
  
=begin rdoc
  find all user contacts
=end
  def Contact.find_by_user( auth, slug, opts = {} )
    raise Oos4ruby::UnknownUser if slug.nil?
    
    uri = CONTACTS_URL + "/#{slug}"
    
    getter = HTTPInvoker.new(uri, auth)
    
    worked = getter.get
    
    Contacts.new(Feed.read(getter.body), auth, slug) if worked
  end
  
=begin rdoc
  returns the user associated with this contact
=end
  def data         
    @data = User.find @auth, @xml.link('userInfo') unless @data
    @data
  end
  
  def trusted?
    trusted = @xml.first("./atom:category[@scheme=\"#{TRUSTED_URL}\"]")
    trusted = Category.new trusted
    trusted.term.downcase == 'true'
  end
  
  def Contact.dump!(opts, slug)
    entry = create_entry
    
    entry.add_element opts[:author]

    updated = DateTime::now.strftime("%Y-%m-%dT%H:%M:%S%z").sub(/(..)$/, ':\1')
    
    add_element entry, 'updated', updated
    add_element entry, 'id', make_id
    
    add_element entry, 'title', (opts[:contact] || opts[:slug] || opts[:title])
    add_element entry, 'content', ''
    
    if opts[:trusted]
      if opts[:trusted].is_a?REXML::Element
        entry.add_element opts[:trusted]
      else      
        add_category entry, opts[:trusted], TRUSTED_URL
      end
    end
    
    entry
  end
    
  private
  def load!
    update_category @trusted, TRUSTED_URL, nil, TRUSTED_URL unless @trusted.nil?
    @xml.add_child('content', nil, nil, {:type => 'html'})
  end
  
end
end


